let socketTask = null
let onInitServiceCallback = null
let onSing = null
let onSingAck = null
let onRest = null
let onIdle = null
let onStatus = null
let connected = false;

function initService() {
  socketTask = wx.connectSocket({
    url: 'ws://mido.fibar.cn/'
  })
  socketTask.onOpen(function (res) {
    console.log('WebSocket连接已打开！')
    connected = true;
    if (onInitServiceCallback != null) {
      onInitServiceCallback(1);
    }
  })
  socketTask.onError(function (res) {
    console.log('WebSocket错误' + res)
    if (onInitServiceCallback != null) {
      onInitServiceCallback(0);
    }
  })
  socketTask.onClose(function (res) {
    console.log('WebSocket连接关闭！')
  })
  socketTask.onMessage(function (res) {
    console.log("onMessage: " + res.data)
    let data = JSON.parse(res.data);
    if (data["body"]["status"] == "1") {
      onSing && onSing(data)
    } else if (data["body"]["status"] == "2") {
      onSingAck(data)
    } else if (data["body"]["status"] == "3") {
      onRest(data)
    } else if (data["body"]["status"] == "4") {
      onIdle(data)
    } else if (data["body"]["status"] == "0") {
      onStatus(data)
    }
  })
}

function setOnInitCallback(callback) {
  onInitServiceCallback = callback
}

function setOnSingCallback(callback) {
  onSing = callback
}

function setOnSingAckCallback(callback) {
  onSingAck = callback
}

function setOnRestCallback(callback) {
  onRest = callback
}

function setOnStatusCallback(callback) {
  onStatus = callback
}

function setOnIdleCallback(callback) {
  onIdle = callback
}

function join(fullname, token, room) {
  let data = {
    action: 'join',
    fullname: fullname,
    token: token,
    room: room
  }
  send(data);
}


function sing(fullname, token, room, sid, duration) {
  let data = {
    action: 'sing',
    fullname: fullname,
    token: token,
    room: room,
    sid: sid,
    duration: duration
  }
  send(data)
}

function cut(fullname, token, room) {
  let data = {
    action: 'cut',
    fullname: fullname,
    token: token,
    room: room,
  }
  send(data)
}

function ask(fullname, token, room, ask, duration) {
  let data = {
    action: 'ask',
    fullname: fullname,
    token: token,
    room: room,
    ack: ask,
    duration:duration,
  }
  send(data)
}

function status(fullname, token, room) {
  let data = {
    action: 'status',
    fullname: fullname,
    token: token,
    room: room,
  }
  send(data)
}

function send(data) {
  console.log("send: " + JSON.stringify(data))
  socketTask.send({ data: JSON.stringify(data) })
}

function destroyService() {
  socketTask.close();
}


module.exports = {
  init: initService,
  destroy: destroyService,
  setOnInitCallback: setOnInitCallback,
  setOnSingCallback: setOnSingCallback,
  setOnSingAckCallback: setOnSingAckCallback,
  setOnRestCallback: setOnRestCallback,
  setOnIdleCallback: setOnIdleCallback,
  setOnStatusCallback: setOnStatusCallback,
  sing:sing,
  ask:ask,
  join:join,
  cut:cut,
  status:status
}